<?php


namespace app\common\cachemodel;


use app\common\cachemodel\live\LiveCouponActiveGiveRecord;
use app\common\lib\Push;
use app\common\lib\SensorsData;
use app\common\lib\Util;
use app\common\model\BaseCache;
use app\common\model\Goods;
use app\common\model\MessageCenter;
use GuzzleHttp\Exception\GuzzleException;
use think\Config;
use think\Exception;
use think\Log;
use traits\model\SoftDelete;
use XznsTools\cache\CacheManage;

class UserCoupon extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl_user_coupon';
    protected $cacheModel = 'user.coupon';

    use SoftDelete;

    protected $deleteTime = 'delete_time';

    protected $cacheIdKey = 'id';

    public $errorMsg = null; // 错误消息

    public $isGiveTxt = [
        0 => '、本券不可赠与好友使用。',
        1 => '、本券可赠与好友使用，优惠条件以及有效期不变。',
    ];

    public $goodsTypeTLinkConfig = [ // 优惠券类 0=>不跳转 1=>生时矫正 2=>日运 3=>月运 4=>年运 5=>占星地图 6=>占星视频 7=>本命报告 8会员
        0 => [
            'target' => 'local',
            'link' => 'empty',
        ],
        1 => [  //  生时矫正
            'target' => 'local',
            'link' => 'rectification?need_auth=1',
        ],
        2 => [  //  日运
            'target' => 'local',
            'link' => 'day?need_auth=1', // 日运
        ],
        3 => [  //  月运
            'target' => 'local',
            'link' => 'fortune_for_month?need_auth=1',   // 月运
        ],
        4 => [  //  年运
            'target' => 'local',
            'link' => 'fortune_for_year?need_auth=1',   // 年运
        ],
        5 => [  //  占星地图
            'target' => 'local',
            'link' => 'acg_map?need_auth=1', // 地图首页,默认当前用户自己的档案
        ],
        6 => [  //  占星视频
            'target' => 'local',
            'link' => 'course_list?need_auth=0', // 课程广场
        ],
        7 => [  //  本命报告
            'target' => 'local',
            'link' => 'report_index?need_auth=1',    // 报告首页
        ],
        8 => [  //  会员
            'target' => 'local',
            'link' => 'vip_center?from=2&need_auth=2',   // 会员中心购买页
        ],
        16 => [
            'target' => 'local',
            'link' => "divination_question?type=3&name1=%E5%8D%A0%E6%98%9F%E9%AA%B0%E5%AD%90&name2=%E5%A1%94%E7%BD%97%E5%8D%A0%E5%8D%9C&need_auth=0",   // 塔罗
        ],
        17 => [
            'target' => 'local',
            'link' => 'synastry_report_detail?rid1=0&rid2=0&srid=1&need_auth=1',   // 合盘报告下单页
        ],
        23 => [
            'target' => 'local',
            'link' => 'relation_research_home?need_auth=0',    // 关系研究所首页
        ],
        24 => [
            'target' => 'local',
            'link' => 'relation_research_home?need_auth=0',    // 关系研究所首页
        ],
        25 => [
            'target' => 'local',
            'link' => 'relation_research_home?need_auth=0',    // 关系研究所首页
        ],
        26 => [
            'target' => 'local',
            'link' => 'relation_research_home?need_auth=0',    // 关系研究所首页
        ],
        27 => [  //  年运拓展
            'target' => 'local',
            'link' => 'fortune_for_year?need_auth=1',   // 年运
        ],
        28 => [  //  八字
            'target' => 'local',
            'link' => 'horoscope_home?need_auth=1',   // 八字排盘 首页
        ],
        29 => [  //  冥想课程
            'target' => 'local',
            'link' => 'meditate_list?type=0&need_auth=0',   // 冥想课程列表
        ],
        32 => [  //  冥想课程
            'target' => 'local',
            'link' => 'acquired_astro_index?pay_suc=0&need_auth=0',   // 后天星座
        ],
        100 => [
            'target' => 'local',
            'link' => 'consult_astr_ask?need_auth=2',   // 立即咨询
        ],
    ];

    public $couponTypeName = [
        1 => '折扣',
        2 => '立减',
        3 => '满减',
        4 => '随机',
        5 => '免费',
    ];

    /**
     * 获取卡卷数据
     * @param $uid int 用户id
     * @param $type int 1未使用 2可赠与 3已失效
     * @param bool $isPaging 是否分页
     * @return array|mixed
     * @throws \Exception
     */
    public function getList(int $uid, int $type, $isPaging = true)
    {
        $page = input('page', 1);
        $limit = $this->pageLimit ?: Config::get('paginate.list_rows');

        if (!$isPaging)
        {
            $page = -1; // 获取所有数据
        }

        $sortKey = $type === 3 ? 'update_time' : 'id';

        $data = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setPage($page)
            ->setPageSize($limit)
            ->setSort('desc')
            ->setListKeyType($type)
            ->getListPage(function ($ids = [], $isCache = true, $sortType = 'desc') use ($uid, $type)
            {
                if ($isCache)
                { // 开启了缓存
                    return $this->getInfoByIdsInData($ids, [$uid, $type], $sortType);
                } else
                { // 没开启缓存
                    return $this->getPaginateInData([$uid, $type], $sortType);
                }
            }, $sortKey, [], 0, 'list', 'list_details');

        $pageData = array_filter($data['data']);

        if (count($pageData) !== count($data['data']))
        {
            CacheManage::getInstance()
                ->setCacheConfig($this->cacheModel, $uid)
                ->setListKeyType($type)->rmCache('list');
        }
        $pageData = $this->dataInit($pageData);
        $data['data'] = $pageData;
        if (!$isPaging)
        {
            return $data['data'];
        }

        return $data;
    }

    /**
     * 数据格式
     * @param array $list
     * @return array
     */
    public function dataFormatting(array $list)
    {
        if (empty($list)) return [];

        $data = [];
        $urIds = array_column($list, 'ur_id');
        $urData = (new CouponUseRange())->getInfoByIds($urIds);

        foreach ($list as $k => $arrayData)
        {
            $isGive = $arrayData['is_give'] ?? 0;
            $urInfo = array_filter($urData[$arrayData['ur_id']] ?? []);
            $urInfo[] = (count($urInfo) + 1) . $this->isGiveTxt[$isGive];
            $ctype = (int)($arrayData['use_range'] ?? 0);

            $data[$k] = [
                'cid' => (int)($arrayData['id'] ?? 0),
                'name' => $arrayData['name'] ?? '',
                'desc' => $arrayData['desc'] ?? '',
                'time_des' => $arrayData['end_time'] ? '有效期至' . date('Y.m.d', $arrayData['end_time']) : '',
                'dtype' => (int)($arrayData['type'] ?? 0),
                'discount' => $arrayData['type'] == 4 ? $arrayData['price'] : $arrayData['discount'] ?? '0.0',
                'condition' => (int)($arrayData['condition'] ?? 0),
                'use_rule' => $urInfo,
                'ctype' => $ctype,
                'status' => (int)($arrayData['status'] ?? 0),
                'target' => isset($this->goodsTypeTLinkConfig[$ctype]) ? $this->goodsTypeTLinkConfig[$ctype]['target'] : 'local',
                'link' => isset($this->goodsTypeTLinkConfig[$ctype]) ? $this->goodsTypeTLinkConfig[$ctype]['link'] : 'empty',
            ];

            (new \app\common\cachemodel\Goods())->goodsTargetLink($ctype, $data[$k]['link']);
        }

        return $data;
    }

    /**
     * 获取信息
     * @param $ids
     * @param $map
     * @param $sortType
     * @return array|void
     */
    public function getInfoByIdsInData($ids, $map, $sortType)
    {
        try
        {
            $where = [];
            if ($ids)
            {
                $where['uc.id'] = ['in', $ids];
            } else
            {
                $where['uc.uid'] = $map[0];
                if ($map[1] === 1)
                {   // 未使用
                    $where['uc.status'] = 0;
                    $this->order("uc.id {$sortType}");
                } elseif ($map[1] === 2)
                {   // 可赠与
                    $where['uc.status'] = 0; // 未使用
                    $where['uc.is_give'] = 1; // 可赠与
                    $this->order("uc.id {$sortType}");
                } elseif ($map[1] === 3)
                {   // 已过期失效
                    $where['uc.status'] = ['in', [1, 2, 3, 4]];
                    $this->order('uc.update_time desc');
                }
            }

            $data = $this->alias('uc')
                ->join('wechat_backup_07_18_14_43_00.zl_coupon_attr ca', 'ca.id=uc.c_id')
                ->where($where)
                ->column('ca.name,ca.desc,ca.gids,ca.type,ca.discount,ca.condition,ca.use_range,uc.end_time,uc.price,uc.ur_id,uc.start_time,uc.give_time,uc.status,uc.is_give,uc.uid,uc.c_id,uc.update_time,uc.live_id', 'uc.id');

            foreach ($data as $k => $v)
            {
                $data[$k]['discount'] = $v['discount'] / 100;
            }
        }
        catch (Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'type', 'condition', 'use_range', 'ur_id', 'start_time', 'end_time', 'status', 'is_give', 'uid', 'c_id', 'live_id', 'update_time', 'give_time']);
        }

        return $data;
    }


    /**
     * 获取信息
     * @param $map
     * @param $sortType
     * @return array|void
     */
    public function getPaginateInData($map, $sortType)
    {
        try
        {
            $where = [];

            $where['uc.uid'] = $map[0];
            if ($map[1] === 1)
            {   // 未使用
                $where['uc.status'] = 0;
            } elseif ($map[1] === 2)
            {   // 可赠与
                $where['uc.status'] = 0; // 未使用
                $where['uc.is_give'] = 1; // 可赠与
            } elseif ($map[1] === 3)
            {   // 已过期失效
                $where['uc.status'] = 3;
            }

            $data = $this->alias('uc')->join('wechat_backup_07_18_14_43_00.zl_coupon_attr ca', 'ca.id=uc.c_id')
                ->where($where)
                ->order("uc.id {$sortType}")
                ->field('uc.id,ca.name,ca.desc,ca.gids,ca.type,ca.discount,ca.condition,ca.use_range,uc.end_time,uc.price,uc.ur_id,uc.start_time,uc.give_time,uc.status,uc.is_give,uc.c_id,uc.uid')->paginate()->toArray();

            foreach ($data['data'] as $k => $v)
            {
                $data['data'][$k]['discount'] = $v['discount'] / 100;
            }
        }
        catch (Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    /**
     * 优惠券领取
     * @param $uid
     * @param array $cData
     * @return bool
     * @throws \Exception
     */
    public function add($uid, array $cData): bool
    {
        try
        {
            $resData = $this->saveAll($cData);
            $isGiveIds = [];
            $ids = [];
            foreach ($resData as $item)
            {
                if ($item['is_give'] == 1)
                {
                    $isGiveIds[$item['id']] = $item['id'];
                }
                $ids[$item['id']] = $item['id'];
            }
        }
        catch (\Exception $e)
        {
            return false;
        }

        $this->listDataAdd($uid, $ids, 1); // 未使用
        if ($isGiveIds)
        {
            $this->listDataAdd($uid, $isGiveIds, 2); // 可赠与
        }

        return true;
    }

    /**
     * 优惠券使用和退回
     * @param $uid
     * @param $cid
     * @return bool
     * @throws \think\exception\PDOException
     * @throws \Exception
     */
    public function use_return($uid, $cid, $map)
    {
        $couponInfo = $this->getInfoById($cid);

        if (empty($couponInfo) || $uid != $couponInfo['uid'])
        {   // 判断优惠券使用存在
            $this->errorMsg = '优惠券不存在！';
            return false;
        }

        try
        {
            //live_coupon_active_give_record优惠券活动领取优惠券记录使用时间重置
            if (isset($map['status']))
            {
                if (in_array($map['status'], [1, 2]))
                {
                    (new LiveCouponActiveGiveRecord())->updateData($cid, ['use_coupon_time' => time()]);
                } elseif ($map['status'] == 0)
                {
                    (new LiveCouponActiveGiveRecord())->updateData($cid, ['use_coupon_time' => 0]);
                }
            }
            $this->save($map, ['id' => $cid]);
        }
        catch (Exception $e)
        {
            $this->errorMsg = '服务异常';
            return false;
        }
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $cid)->rmCache();
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setListKeyType(1)->rmCache('list');
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setListKeyType(2)->rmCache('list');
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setListKeyType(3)->rmCache('list');
        return true;
    }

    /**
     * 优惠券删除
     * @param int $uid
     * @param int $cid
     * @return bool
     * @throws \Exception
     */
    public function couponDel(int $uid, int $cid)
    {
        $couponInfo = $this->getInfoById($cid);

        if (empty($couponInfo) || $uid != $couponInfo['uid'])
        {   // 判断优惠券使用存在
            $this->errorMsg = '优惠券不存在！';
            return false;
        }
        try
        {
            self::destroy($cid); // 软删除
        }
        catch (Exception $e)
        {
            $this->errorMsg = '服务异常';
            return false;
        }
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $cid)->rmCache();
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setListKeyType(1)->rmCache('list');
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setListKeyType(2)->rmCache('list');
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setListKeyType(3)->rmCache('list');
        return true;
    }

    /**
     * 用户优惠券赠送
     * @param int $uid1 赠送用户ID
     * @param int $uid2 受赠用户ID
     * @param int $cId 所赠送的优惠券ID
     * @return bool
     * @throws \Exception
     */
    public function couponGive(int $uid1, int $uid2, int $cId, array $userInfo): bool
    {
        $couponInfo = $this->getInfoById($cId);

        if (empty($couponInfo) || $uid1 != $couponInfo['uid'])
        {   // 判断优惠券使用存在
            $this->errorMsg = '赠送的优惠券不存在！';
            return false;
        }

        if ($couponInfo['is_give'] != 1)
        {   // 判断优惠券是否可以赠送
            $this->errorMsg = '该优惠券不可赠送！';
            return false;
        }

        if ($couponInfo['status'] != 0)
        {   // 判断优惠券是否可以赠送
            $this->errorMsg = '优惠券过期；赠送失败';
            return false;
        }

        $this->startTrans();
        try
        {
            $time = time();
            $this->save(['status' => 2, 'update_time' => $time], ['id' => $cId]); // 优惠券状态更新为已赠送
            $couponData = [
                'uid' => $uid2,
                'c_id' => $couponInfo['c_id'],
                'ur_id' => $couponInfo['ur_id'],
                'start_time' => $time,
                'end_time' => $couponInfo['end_time'],
                'give_time' => $time,
                'status' => 0,
                'price' => $couponInfo['price'],
                'is_give' => 0,
                'create_time' => $time,
                'update_time' => 0,
            ];
            // 给被赠送用户增加优惠券
            $newCid = $this->insertGetId($couponData);

            $giveRecord = [
                'uid' => $uid1,
                'give_uid' => $uid2,
                'cdesc' => $couponInfo['desc'],
                'uc_id' => $cId,
                'new_uc_id' => $newCid,
                'give_type' => 1,
                'create_time' => $time,
            ];
            // 写入赠送历史
            $recordId = (new UserCouponGiveRecord())->insertGetId($giveRecord);
            $this->commit();
        }
        catch (Exception $e)
        {
            $this->rollback();
            $this->errorMsg = '服务异常';
            return false;
        }

        // 消息中心添加信息
        $messageData = [
            'status' => 0,
            'is_read' => 0,
            'range' => $uid2,
            'type' => 2,
            'reid' => 0,
            'cid' => 0,
            'title' => '卡券获赠提醒',
            'content' => "您的好友：{$userInfo['nickname']}（准了号{$userInfo['uen']}）赠送您一张【{$couponInfo['desc']}】已放入您的【卡券中心】快去使用吧~",
            'link' => 'discount_coupon_center?need_auth=2',
            'target' => 'local',
            'create_time' => time(),
        ];
        //发送消息
        try
        {
            (new Push())->pushUserMsg($uid2, $messageData['content'], ['action' => 'discount_coupon_center'], $messageData['title']);
            (new MessageCenter())->pushMessage($uid2, $messageData);
        }
        catch (Exception $e)
        {
            print("会员 写入消息中心失败: " . $e->getMessage() . PHP_EOL);
            Log::write("会员 写入消息中心失败: " . $e->getMessage() . PHP_EOL, 'error');
        }

        // 更新缓存
        $this->listDataDel($uid1, [$cId], 1);   // 可用优惠券 赠送用户
        $this->listDataDel($uid1, [$cId], 2);   // 可赠优惠券 赠送用户
        $this->listDataAdd($uid1, [$cId => $time], 3);   // 可用新增 赠送优惠券 失效数据
        $this->listDataAdd($uid2, [$newCid => $newCid], 1);   // 可用新增 被赠用户
        // 更新优惠券缓存
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $cId)->setCache(['status' => 2, 'update_time' => $time]);
        $userCouponGiveRecord = new UserCouponGiveRecord();
        $userCouponGiveRecord->listDataAdd($uid1, [$recordId => $recordId], 0); // 新增 赠送用户 赠送历史
        $userCouponGiveRecord->listDataAdd($uid2, [$recordId => $recordId], 0); // 新增 被赠用户 赠送历史

        $gidsArr = explode(',', $couponInfo['gids']);

        $couponRangeArr = (new Goods())->where('id', 'in', $gidsArr)->column('name');

        // 神策打点 75 获得优惠券 AcquireCoupon
        SensorsData::track($uid2, true, 'AcquireCoupon', [
            'refer_name' => '',
            'refer_link' => '',
            'coupon_name' => $couponInfo['name'],
            'coupon_expire' => date('Y-m-d H:i:s', $couponInfo['end_time']),
            'coupon_type' => $this->couponTypeName[$couponInfo['type']],
            'coupon_range' => $couponRangeArr,
            'acquire_channel' => '朋友赠送',
            'is_give' => false,
            'acquire_scene' => '朋友赠送',
        ]);

        return true;
    }

    /**
     * 通过商品id和
     * @param int $uid 用户ID
     * @param array $gids 商品ID集合
     * @param string|float $price 支付金额
     * @return array
     * @throws \Exception
     */
    public function getUsableList(int $uid, array $gids, $price): array
    {
        $couponList = $this->getList($uid, 1, false);

        $list = [];
        $data = [];
        foreach ($couponList as $key => $item)
        {
            if (!empty($item['gids']) && array_diff($gids, explode(',', $item['gids']))) continue;

            $data[$item['id']] = $item;
            switch ($item['type'])
            {
                case 1:
                    // 折扣券
                    $discountAmount = sprintf('%.2f', $price - ($price * $item['discount'])); // 获取优惠金额
                    $list[$item['id']] = $discountAmount;
                    break;
                case 2:
                case 3:
                    // 立减券和满减券
                    if ($price > $item['condition']) $list[$item['id']] = $item['discount'];
                    break;
                case 4:
                    // 随机券
                    $list[$item['id']] = $item['price'];
                    break;
                case 5:
                    // 全免券
                    $list[$item['id']] = $price;
                    break;
                default:
            }
        }

        arsort($list);

        $listData = [];
        foreach ($list as $cid => $discountAmount)
        {
            $listData[] = $data[$cid];
        }

        return $listData;
    }

    /**
     * 购买学业报告赠送《幸运之城》-智慧线 免费券
     * 活动赠送优惠券
     * @param int $uid
     */
    public function activeSendCoupon(int $uid)
    {
        $couponId = 256; // 《幸运之城》-智慧线 免费券 优惠券ID
        // 查询优惠券具体属性
        $couponDetail = (new ZlCouponAttr())->field('name,desc,type,gids,ur_id')->where('id', $couponId)->findOrFail();
        $time = time();

        $cData = [
            'uid' => $uid,
            'c_id' => $couponId,
            'ur_id' => $couponDetail['ur_id'],
            'start_time' => $time,
            'end_time' => strtotime('+30 day', $time),
            'give_time' => $time,
            'status' => 0,
            'price' => 0,
            'is_give' => 0,
            'create_time' => $time,
            'update_time' => 0,
        ];

        // 写入用户卡券中心
        $ucId = $this->insertGetId($cData);
        // 更新用户卡券中心缓存
        $this->listDataAdd($uid, [$ucId => $ucId], 1);
        // 发送推送 通知消息
        // PUSH推送
        (new Push())->pushUserMsg($uid, '恭喜您获得智慧命格线，快来查看吧！', ['action' => 'discount_coupon_center']);
        // 消息中心添加信息
        $messageData = [
            'status' => 0,
            'is_read' => 0,
            'range' => $uid,
            'type' => 2,
            'reid' => 0,
            'cid' => 0,
            'title' => '智慧线优惠券获取成功！',
            'content' => "恭喜您获得幸运之城-智慧线免费券，赶快点击查看吧！",
            'link' => 'discount_coupon_center?need_auth=2',
            'target' => 'local',
            'create_time' => time(),
        ];
        //发送消息
        try
        {
            (new MessageCenter())->pushMessage($uid, $messageData);
        }
        catch (\Exception $e)
        {
            print("购买学业报告赠送优惠券 写入消息中心失败: " . $e->getMessage() . PHP_EOL);
            Log::write("购买学业报告赠送优惠券 写入消息中心失败: " . $e->getMessage() . PHP_EOL, 'error');
        }
        // 神策打点
        $gidsArr = explode(',', $couponDetail['gids']);
        $couponRangeArr = (new Goods())->where('id', 'in', $gidsArr)->column('name');
        // 神策打点 75 获得优惠券 AcquireCoupon
        SensorsData::track($uid, true, 'AcquireCoupon', [
            'refer_name' => '',
            'refer_link' => '',
            'coupon_name' => $couponDetail['desc'],
            'coupon_expire' => date('Y-m-d H:i:s', $cData['end_time']),
            'coupon_type' => $this->couponTypeName[$couponDetail['type']],
            'coupon_range' => $couponRangeArr,
            'acquire_channel' => '2021.07学业报告赠智慧线',
            'is_give' => false,
            'acquire_scene' => '系统赠送',
        ]);
    }

    /**
     * 2021七夕活动，赠送恋爱合盘报告免费券
     * 活动赠送优惠券
     * @param int $uid
     */
    public function activeSendCoupon2(int $uid)
    {
        $couponId = 257; // 2021七夕活动合盘报告八折券
        // 查询优惠券具体属性
        $couponDetail = (new ZlCouponAttr())->field('name,desc,type,gids,ur_id')->where('id', $couponId)->findOrFail();
        $time = time();

        $cData = [
            'uid' => $uid,
            'c_id' => $couponId,
            'ur_id' => $couponDetail['ur_id'],
            'start_time' => $time,
            'end_time' => strtotime('+7 day', $time),
            'give_time' => $time,
            'status' => 0,
            'price' => 0,
            'is_give' => 0,
            'create_time' => $time,
            'update_time' => 0,
        ];

        // 写入用户卡券中心
        $ucId = $this->insertGetId($cData);
        // 更新用户卡券中心缓存
        $this->listDataAdd($uid, [$ucId => $ucId], 1);
        // 发送推送 通知消息
//        // PUSH推送
//        (new Push())->pushUserMsg(
//            $uid,
//            '您已成功获得七夕活动合盘报告八折券一张，优惠券有效期7天，小行星要尽快使用哦~',
//            ['action' => 'discount_coupon_center'],
//            '准了'
//        );
        // 消息中心添加信息
        $messageData = [
            'status' => 0,
            'is_read' => 0,
            'range' => $uid,
            'type' => 2,
            'reid' => 0,
            'cid' => 0,
            'title' => '七夕活动奖励通知',
            'content' => "您已成功获得七夕活动合盘报告八折券一张，优惠券有效期7天，小行星要尽快使用哦~",
            'link' => 'discount_coupon_center?need_auth=2',
            'target' => 'local',
            'create_time' => $time,
        ];
        //发送消息
        try
        {
            (new MessageCenter())->pushMessage($uid, $messageData);
        }
        catch (\Exception $e)
        {
            print("2021七夕活动赠送优惠券 写入消息中心失败: " . $e->getMessage() . PHP_EOL);
            Log::write("2021七夕活动赠送优惠券 写入消息中心失败: " . $e->getMessage() . PHP_EOL, 'error');
        }
        // 神策打点
        $gidsArr = explode(',', $couponDetail['gids']);
        $couponRangeArr = (new Goods())->where('id', 'in', $gidsArr)->column('name');
        // 神策打点 75 获得优惠券 AcquireCoupon
        SensorsData::track($uid, true, 'AcquireCoupon', [
            'refer_name' => '',
            'refer_link' => '',
            'coupon_name' => $couponDetail['desc'],
            'coupon_expire' => date('Y-m-d H:i:s', $cData['end_time']),
            'coupon_type' => $this->couponTypeName[$couponDetail['type']],
            'coupon_range' => $couponRangeArr,
            'acquire_channel' => '2021七夕',
            'is_give' => false,
            'acquire_scene' => '系统赠送',
        ]);
    }

    /**
     * 系统赠送用户优惠券
     * @param int $uid 赠送用户ID
     * @param int $cId 所赠送的优惠券ID
     * @param int $num 赠送数量
     * @param string $order_id
     * @return bool
     * @throws GuzzleException
     */
    public function systemCouponGive(int $uid, int $cId, int $num, string $order_id): bool
    {
        try
        {
            $nowTime = time();
            // 发放优惠券
            $userCouponModel = new UserCoupon();
            $couponInfo = (new ZlCouponAttr())->getInfoById($cId, ['desc', 'type', 'rand_min', 'rand_max', 'ur_id', 'use_range']);
            $userCids = [];
            for ($i = 1; $i <= $num; $i++)
            {
                $cData = [
                    'uid' => $uid,
                    'c_id' => $cId,
                    'ur_id' => $couponInfo['ur_id'],
                    'start_time' => $nowTime,
                    'end_time' => strtotime("+30 day"),  // 有效期 30 天
                    'give_time' => $nowTime,
                    'status' => 0,
                    'price' => $couponInfo['type'] == 4 ? random_int($couponInfo['rand_min'], $couponInfo['rand_max']) : 0,
                    'is_give' => 0,
                    'create_time' => $nowTime,
                    'update_time' => 0,
                ];
                $ucId = $userCouponModel->insertGetId($cData);
                $userCids[$ucId] = (int)$ucId;
            }
            // 未使用
            $userCouponModel->listDataAdd($uid, $userCids, 1);

            $couponTypeName = $couponInfo['use_range'] == 4 ? '年运' : '月运';
            // 消息中心添加信息
            $messageData = [
                'status' => 0,
                'is_read' => 0,
                'range' => $uid,
                'type' => 2,
                'reid' => 0,
                'cid' => 0,
                'title' => '组合商品购买成功',
                'content' => "{$couponInfo['desc']}已发放到你的卡券中心，请尽快使用～使用方法：{$couponTypeName}下单时，请在确认订单页，选择优惠券进行使用。",
                'link' => 'discount_coupon_center?need_auth=2',
                'target' => 'local',
                'create_time' => $nowTime,
            ];
            (new MessageCenter())->pushMessage($uid, $messageData);
            (new Push())->pushUserMsg($uid, "{$couponInfo['desc']}已发放到你的卡券中心，请尽快使用～使用方法：{$couponTypeName}下单时，请在确认订单页，选择优惠券进行使用。", ['action' => 'extend', 'target' => 'local', 'link' => "discount_coupon_center?need_auth=2"], '组合商品购买成功');
            $userInfo = (new \app\common\model\User())->getUserinfo(['id' => $uid]);
            Util::sendHySms([$userInfo['tel']], '', 93287, ['good_des' => '组合商品中的' . $couponInfo['desc'], 'others' => $couponTypeName]);
        }
        catch (\Exception $e)
        {
            Log::write($order_id . '赠送优惠券异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error');
            return false;
        }
        return true;
    }

    /**
     * 获取 本次连线 使用最佳的优惠券信息
     * @param int $uid
     * @param int $min 连线时长【分钟】
     * @return array | null
     * @throws \Exception
     */
    public function getConsultUseCouponInfo(int $uid, int $min)
    {
        $couponDatas = $this->getList($uid, 1, false);
        $resData = null;
        $nowTime = time();
        foreach ($couponDatas as $couponDataItem)
        {
            if ($couponDataItem['status'] > 0 || $nowTime >= $couponDataItem['end_time'])
            {   // 优惠券 已使用 或 已过期
                continue;
            }
            if ((int)$couponDataItem['use_range'] !== 100)
            {
                continue;
            }
            if ($min >= $couponDataItem['condition'])
            {   // 是否符合满减条件
                if ($resData)
                {
                    if ($resData['discount'] > $couponDataItem['discount'])
                    {   // 满减时长 太小
                        continue;
                    }
                    if ($resData['discount'] === $couponDataItem['discount'])
                    {   // 满减时长相同
                        if ($resData['condition'] > $couponDataItem['condition'])
                        {   // 满减条件 太小
                            continue;
                        }
                        if ($resData['condition'] === $couponDataItem['condition'] && $resData['end_time'] <= $couponDataItem['end_time'])
                        {   // 满减条件 相同 且 过期时间更长或相同
                            continue;
                        }
                    }
                }

                $resData = [
                    'id' => $couponDataItem['id'],
                    'end_time' => $couponDataItem['end_time'],      // 过期时间
                    'condition' => $couponDataItem['condition'],    // 满减条件[分钟]
                    'discount' => $couponDataItem['discount'],      // 满减时长[分钟]
                ];
            }
        }

        return $resData;
    }

    /**
     * @param int $uid
     * @return array
     * @throws \Exception
     */
    public function getConsultRtcCids(int $uid)
    {
        $couponDatas = $this->getList($uid, 1, false);
        $cids = [];
        $nowTime = time();
        foreach ($couponDatas as $couponDataItem)
        {
            if ($couponDataItem['status'] > 0 || $nowTime >= $couponDataItem['end_time'])
            {   // 优惠券 已使用 或 已过期
                continue;
            }
            if ($couponDataItem['use_range'] !== 100)
            {
                continue;
            }
            $cids[] = $couponDataItem['id'];
        }
        return $cids;
    }
}
